<template>
  <view>
    <t-cell
      v-if="showCell"
      :title="title"
      arrow
      :note="locationModel || '--'"
      @click="show"
    />

    <t-popup v-model="visibleModel" placement="center">
      <view class="map-box">
        <view class="search-box">
          <t-input
            v-model:value="address"
            placeholder="请输入地址搜索"
            @change="Doserach"
          >
            <template #suffix>
              <t-icon name="search" />
            </template>
          </t-input>
        </view>
        <view class="btn-box">
          <t-button
            size="large"
            theme="primary"
            shape="round"
            block
            @click="handleConfirm"
            >确认</t-button
          >
        </view>
        <GAmap ref="baseAmap" :option="mapOption" @loaded="mapLoaded" />
      </view>
    </t-popup>
  </view>
</template>

<script setup>
import {
  ref,
  defineProps,
  defineEmits,
  reactive,
  nextTick,
  watchEffect,
} from "vue";
import { useVModel } from "@vueuse/core";
import { isBoolean } from "lodash-es";
import GAmap from "@/components/GAmap/GAmap.vue";

const props = defineProps({
  showCell: {
    type: Boolean,
    default: true,
  },
  visible: {
    type: [String, Boolean],
    default: "",
  },
  lng: {
    type: String,
    default: "",
  },
  lat: {
    type: String,
    default: "",
  },
  location: {
    type: String,
    default: "",
  },
  disabled: {
    type: Boolean,
    default: false,
  },
  title: {
    type: String,
    default: "单个选择日期",
  },
});
const emits = defineEmits([
  "update:visible",
  "update:lng",
  "update:lat",
  "update:location",
]);

const lngModel = useVModel(props, "lng", emits);
const latModel = useVModel(props, "lat", emits);
const locationModel = useVModel(props, "location", emits);

const visibleModel = isBoolean(props.visible)
  ? useVModel(props, "visible", emits)
  : ref(false);
const baseAmap = ref();
const address = ref("");
const formData = reactive({
  lng: "",
  lat: "",
  location: "",
});

watchEffect(() => {
  formData.lng = lngModel.value;
  formData.lat = latModel.value;
  formData.location = locationModel.value;
});

const show = () => {
  if (props.disabled) return;

  visibleModel.value = true;
};

const mapOption = reactive({
  center: [104.0668, 30.5728],
});

/* 地图初始化之后 */
const mapLoaded = () => {
  if (formData.lng && formData.lat) {
    const lng = formData.lng;
    const lat = formData.lat;
    baseAmap.value.map.clearMap();
    const marker = new baseAmap.value.AMap.Marker({
      position: [Number(lng), Number(lat)],
    });
    marker.setMap(baseAmap.value.map);
    baseAmap.value.map.setCenter([Number(lng), Number(lat)]);
  }
  baseAmap.value.map.on("click", (e) => {
    nextTick(() => {
      const lng = e.lnglat.getLng();
      const lat = e.lnglat.getLat();
      formData.lng = lng;
      formData.lat = lat;
      baseAmap.value.map.clearMap();
      const marker = new baseAmap.value.AMap.Marker({
        position: [Number(lng), Number(lat)],
      });
      marker.setMap(baseAmap.value.map);
      baseAmap.value.AMap.plugin("AMap.Geocoder", function () {
        var geocoder = new baseAmap.value.AMap.Geocoder({
          // city 指定进行编码查询的城市，支持传入城市名、adcode 和 citycode
          city: "全国",
        });
        geocoder.getAddress([lng, lat], (status, result) => {
          if (status === "complete" && result.regeocode.formattedAddress) {
            address.value = result.regeocode?.formattedAddress;
            formData.location = result.regeocode?.formattedAddress;
          } else {
            message.warning("您选择的地址没有解析到结果");
          }
        });
      });
    });
  });
};

/*  地图搜索 */
const Doserach = () => {
  baseAmap.value.AMap.plugin("AMap.PlaceSearch", function () {
    const place = new baseAmap.value.AMap.PlaceSearch({
      pageIndex: 1,
      pageSize: 10,
      extensions: "all",
    });
    place.search(address.value, (status, res) => {
      // 查询成功时，res 即对应匹配的 POI 信息
      if (res.poiList?.pois) {
        console.log("点位信息：", res.poiList.pois);
        formData.location = address.value;
        const location = res.poiList.pois[0]?.location || {};
        const { lng, lat } = location;
        formData.lng = lng;
        formData.lat = lat;
        baseAmap.value.map.clearMap();
        const stationMarker = new baseAmap.value.AMap.Marker({
          position: [Number(lng), Number(lat)],
        });
        stationMarker.setMap(baseAmap.value.map);
        baseAmap.value.map.setZoomAndCenter(10, [Number(lng), Number(lat)]);
      } else {
        message.warning("您填写的地址没有解析到结果");
      }
    });
  });
};

const handleConfirm = () => {
  //   console.log(val);
  visibleModel.value = false;

  console.log("formData:", formData);
  lngModel.value = formData.lng;
  latModel.value = formData.lat;
  locationModel.value = formData.location;
};

/* const handleSelect = (val) => {
  console.log(val);
};
const onClose = (trigger) => {
  console.log("closed by", trigger);
}; */
</script>

<style lang="less" scoped>
.map-box {
  width: 98vw;
  height: 80vh;
  position: relative;
}

.search-box {
  position: absolute;
  top: 50rpx;
  left: 50rpx;
  right: 50rpx;
  // height: 100rpx;
  z-index: 9;
  border-radius: 20rpx;
  overflow: hidden;
}
.btn-box {
  position: absolute;
  bottom: 50rpx;
  left: 50rpx;
  right: 50rpx;
  z-index: 9;
}
</style>
